package com.one.blocks.rbac.manager;

import com.one.blocks.mvc.manager.AbstractBatchManager;
import com.one.blocks.mvc.util.ScopeWebRequestHelper;
import com.one.blocks.mvc.valid.validator.UniqueManager;
import com.one.blocks.rbac.controller.vo.SysOrgVo;
import com.one.blocks.rbac.domain.SysOrg;
import com.one.blocks.rbac.domain.SysUserOrg;
import com.one.blocks.rbac.mapper.SysOrgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.ConstraintValidatorContext;
import java.util.List;

import static com.one.blocks.rbac.constant.RbacConstant.ScopeRequest.VALID_ORG_CHILDREN_OF_ORG_ID;

/**
 * @author <a href="mailto:idler41@163.con">idler41</a> created on 2023-10-25 10:50:39
 */
@Service
public class SysOrgManager extends AbstractBatchManager<SysOrgMapper, SysOrg> implements UniqueManager<SysOrgVo> {

    @Autowired
    private SysUserOrgManager sysUserOrgManager;

    @Autowired
    public SysOrgManager(SysOrgMapper mapper) {
        super(mapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public void grant(Integer orgId, List<SysUserOrg> sysUserOrgList) {
        sysUserOrgManager.deleteByOrgId(orgId);
        sysUserOrgManager.insertBatch(sysUserOrgList);
    }

    public List<SysOrg> findAllChildrenByFullCode(String fullCode) {
        return mapper.selectByFullCode(fullCode);
    }

    @Override
    public boolean isUnique(SysOrgVo sysOrgVo, ConstraintValidatorContext context) {
        List<SysOrg> childList = ScopeWebRequestHelper.get(VALID_ORG_CHILDREN_OF_ORG_ID + sysOrgVo.getParentId(), () -> mapper.selectByParentId(sysOrgVo.getParentId()));
        // 同层级是否存在重复编码
        return childList.stream().anyMatch(i -> !i.getId().equals(sysOrgVo.getId()) && i.getCode().equals(sysOrgVo.getCode()));
    }
}